# -*- coding:utf-8 -*-
from datetime import datetime, timedelta

from flask import current_app


def timed_write_login_info_count():
    """记录昨日登录总数量"""
    from manager import app
    with app.app_context():
        yesterdayDateStr = (datetime.now() - timedelta(seconds=24 * 3600)).strftime("%Y-%m-%d")
        yesterdayDateStart = datetime.strptime(f"{yesterdayDateStr} 00:00:00", "%Y-%m-%d %H:%M:%S")
        yesterdayDateEnd = datetime.strptime(f"{yesterdayDateStr} 23:59:59", "%Y-%m-%d %H:%M:%S")

        from info.models import LoginInfo, LoginInfoCount
        yesterdayDateLoginCount = 0
        try:
            yesterdayDateLoginCount = LoginInfo.query.filter(LoginInfo.login_time >= yesterdayDateStart,
                                                             LoginInfo.login_time <= yesterdayDateEnd).count()
        except Exception as e:
            current_app.logger.error(e)

        nowLoginInfoCount = None
        try:
            nowLoginInfoCount = LoginInfo.query.filter(LoginInfo.login_time == datetime.strptime(yesterdayDateStr,
                                                                                                 "%Y-%m-%d")).first()
        except Exception as e:
            current_app.logger.error(e)
        if nowLoginInfoCount:
            return

        loginInfoCount = LoginInfoCount()
        loginInfoCount.login_date = datetime.strptime(yesterdayDateStr, "%Y-%m-%d")
        loginInfoCount.count = yesterdayDateLoginCount
        from info import db
        db.session.add(loginInfoCount)
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
